import { api } from "@/api";
import { Icon } from "@iconify/react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useDispatch, useSelector, useStore } from "react-redux";
import { useParams } from "react-router-dom";
import styled from "styled-components";
import CommentField from "./CommentField";
import { useGetState, useMyContext } from "@/hooks";
import { Button, Spin, Avatar } from "antd";
import { LoadingOutlined } from "@ant-design/icons";
import { convertImgUrl } from "@/utils/MyFun";
import { formateDate } from "@/utils/common";
import action from "@/store/action";

const Styled = styled.div`
  margin-bottom: 5rem;
  textarea {
    background: url(https://static.talkxj.com/config/commentBack.webp) 100% 100%
      no-repeat;
    resize: none;
  }
  header {
    display: flex;
    align-items: center;
    font-size: 5rem;
    margin-bottom: 5rem;
  }
  .avatar {
    transition: all 600ms;
    &:hover {
      transform: rotate(360deg);
    }
  }
  .comment-box {
    p.title {
      font-size: 5rem;
      font-weight: 700;
      display: flex;
      align-items: center;
      margin-bottom: 3.5rem;
      span {
        margin-right: 3.75rem;
      }
      .icon {
        font-size: 5.5rem;
      }
    }
    .loading-more {
      text-align: center;
    }
  }
  .comment-content {
    display: flex;

    .content {
      margin-left: 2.5rem;
      flex: 1 1 0%;
      display: flex;
      flex-direction: column;
      a {
        color: #1abc9c;
        font-weight: 500;
      }
      .blog-user-flag {
        background-color: #ffa51e;
        color: #fff;
        border-radius: 0.75rem;
        font-size: 3rem;
        padding-top: 0.25rem;
        padding-bottom: 0.25rem;
        padding-left: 1.5rem;
        padding-right: 1.5rem;
        display: inline-block;
        margin-left: 1.5rem;
      }
    }
  }
  .floor-time-good-reply {
    font-size: 3.5rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .left {
      color: rgba(179, 179, 179, 1);
      padding-top: 1.25rem;
      padding-bottom: 1.25rem;
      display: flex;
      align-items: center;
      .time {
        margin-left: 2.5rem;
        margin-right: 2.5rem;
      }
      .icon {
        cursor: pointer;
        &:hover {
          color: red;
        }
      }
    }
    .right {
      font-family: inherit;
      font-size: 100%;
      font-weight: inherit;
      line-height: inherit;
      color: inherit;
      margin: 0;
      padding: 0;
      text-transform: none;
      -webkit-appearance: button;
      background-color: transparent;
      background-image: none;
      cursor: pointer;
      --un-text-opacity: 1;
      color: rgba(239, 47, 17, var(--un-text-opacity));
      box-sizing: border-box;
      border-width: 0;
      border-style: solid;
      border-color: #e5e7eb;
    }
  }
`;

const Comment = ({ type }) => {
  const { messageApi } = useMyContext();
  const dispatch = useDispatch();
  // type 评论类型 1文章 2友链
  const { appStore, userStore } = useSelector((state) => {
    return {
      appStore: state.app,
      userStore: state.user,
    };
  });

  // url 中存在 id 参数则为 topic_id, 否则为 0
  const topicId = +useParams().id ?? 0;
  // 加载评论
  let [commentList, setCommentList] = useState([]); // 评论列表 (分页加载)
  let [commentCount, setCommentCount] = useState(0); // 评论总数量
  let [listLoading, setListLoading] = useState(false); // 列表加载状态
  const [params, setParams, getParams] = useGetState({
    type,
    page_size: 10,
    page_num: 1,
    topic_id: topicId,
  }); // 加载评论的参数

  const replyFieldRefs = useRef([]); //回复引用

  const getComments = async () => {
    const new_params = getParams();
    setListLoading(true);
    try {
      //防止执行过快，看不清loading效果（可以组件销毁是清除定时器）
      setTimeout(async () => {
        const res = await api.getComments(new_params);
        new_params.page_num === 1
          ? setCommentList(res.data.pageData)
          : setCommentList([...commentList, ...res.data.pageData]);
        setCommentCount(res.data.total);
        setParams({
          ...new_params,
          page_num: new_params.page_num + 1,
        });
        setListLoading(false);
      }, 800);
    } catch (error) {
      console.log(error);
    }
  };

  // 重新加载评论(提交评论以后)
  const reloadComments = async () => {
    setParams({
      ...params,
      page_num: 1,
    });
    await getComments();
  };

  const replyComment = (idx, obj) => {
    //关闭所有的回复框
    replyFieldRefs.current.forEach((e) => e.setReply(false));
    const curRef = replyFieldRefs.current[idx];
    curRef.setReply(true); //设置单个回复框显示
    curRef.setData({
      ...curRef.data,
      nickname: obj.nickname,
      reply_user_id: obj.user_id, //回复用户的id
      parent_id: commentList[idx].id, //父评论的id
    });
  };

  //提交回复，重新加载评论回复
  const checkRefs = useRef();

  const reloadReplies = async (idx) => {
    try {
      const { data } = await api.getCommentReplies(commentList[idx].id);
      let new_commentList = commentList;
      new_commentList[idx].reply_vo_list = data;
      new_commentList[idx].reply_count++;
      setCommentList([...new_commentList]);
    } catch (error) {
      console.log(error);
    }
  };

  //点击查看更多回复
  const checkReplies = async (idx, obj) => {};

  //点赞
  const likeComment = async (comment) => {
    if (!userStore.userInfo.id) {
      messageApi.info("请先登录");
      dispatch(action.app.setLoginFlag(true));
      return;
    }
    try {
      await api.saveLikeComment(comment.id);
      // 判断是否点赞
      if (userStore.userInfo.commentLikeSet.includes(comment.id)) {
        messageApi.info("已取消");
      } else {
        messageApi.info("已点赞");
      }
      dispatch(action.user.commentLike(comment.id));
    } catch (error) {
      console.log(error);
    }
  };

  const isLike = useCallback(
    (id) => {
      return userStore.userInfo.commentLikeSet.includes(id);
    },
    [userStore.userInfo.commentLikeSet]
  );

  useEffect(() => {
    getComments();
  }, []);

  return (
    <Styled>
      <header>
        <Icon icon="fa-solid:comments" color="rgba(96,165,250)" />
        &nbsp;&nbsp;评论
      </header>
      {/* 评论框 */}
      <CommentField
        show={true}
        type={type}
        topicId={topicId}
        afterSubmit={reloadComments}
      />
      {/* 评论详情 */}
      {/* 没有评论的提示 */}
      {commentCount > 0 ? (
        <div className="comment-box">
          <p className="title">
            <span>{commentCount} 评论</span>
            <Icon
              icon="tabler:reload"
              className={`${listLoading ? "animate-spin" : ""} icon`}
              onClick={reloadComments}
            />
          </p>
          {/* 评论 */}
          {commentList.map((comment, idx) => {
            return (
              <div className="comment-content" key={comment.id}>
                <div>
                  <Avatar
                    className="avatar"
                    src={convertImgUrl(comment.avatar)}
                    size={40}
                  />
                </div>
                <div className="content">
                  {/* 评论人名称 */}
                  <p>
                    {/* 根据是否有website显示不同效果 */}
                    {!comment.website ? (
                      <span>{comment.nickname}</span>
                    ) : (
                      <a href={comment.website} target="_blank">
                        {comment.nickname}
                      </a>
                    )}
                    {+comment.user_id === +userStore.userInfo.id ? (
                      <span className="blog-user-flag">博主</span>
                    ) : null}
                  </p>
                  {/* 楼层 + 时间 + 点赞 + 回复按钮  */}
                  <div className="floor-time-good-reply">
                    {/* 左右布局 */}
                    <div className="left">
                      <span>{commentCount - idx}楼</span>
                      <span className="time">
                        {formateDate(comment.create_at)}
                      </span>
                      <Icon
                        className="icon"
                        style={{
                          color: `${isLike(comment.id) ? "red" : ""}`,
                        }}
                        icon="icon-park-outline:good-two"
                        onClick={likeComment.bind(null, comment)}
                      />
                      {/* 控制display的none切换 */}
                      {/* <span
                        style={{
                          display: comment.like_count ? "inline" : "none",
                        }}
                      >
                        {comment.like_count}
                      </span> */}
                    </div>
                    <button
                      className="right"
                      onClick={replyComment.bind(null, idx, comment)}
                    >
                      回复
                    </button>
                  </div>

                  {/* 评论内容 */}
                  <div
                    style={{
                      marginTop: "0.75rem",
                      marginBottom: "0.75rem",
                    }}
                    dangerouslySetInnerHTML={{ __html: comment.content }}
                  />

                  {/* 评论回复 */}
                  {comment.reply_vo_list.map((reply) => {
                    return (
                      <div key={reply.id} className="comment-content">
                        <div>
                          <Avatar
                            className="avatar"
                            size={40}
                            src={convertImgUrl(reply.avatar)}
                          />
                        </div>
                        <div className="content">
                          {/* 回复人名称 */}
                          <div>
                            {!reply.website ? (
                              <span>{reply.nickname}</span>
                            ) : (
                              <a href={reply.website} target="_blank">
                                {reply.nickname}
                              </a>
                            )}
                            {reply.user_id === 10 ? (
                              <span className="blog-user-flag">博主</span>
                            ) : null}
                          </div>
                          {/* 时间 + 点赞 + 回复按钮 */}
                          <div className="floor-time-good-reply">
                            <div className="left">
                              <span
                                className="time"
                                style={{ marginLeft: "0" }}
                              >
                                {formateDate(reply.create_at)}
                              </span>
                              <Icon
                                className="icon"
                                style={{
                                  color: `${isLike(reply.id) ? "red" : ""}`,
                                }}
                                icon="icon-park-outline:good-two"
                                onClick={likeComment.bind(null, reply)}
                              />
                            </div>
                            <button
                              className="right"
                              onClick={() => {
                                replyComment(idx, reply);
                              }}
                            >
                              回复
                            </button>
                          </div>
                          {/* 回复内容 */}
                          <div>
                            {reply.reply_user_id !== comment.user_id ? (
                              <>
                                {!reply.reply_website ? (
                                  <span>@{reply.reply_nickname}</span>
                                ) : (
                                  <a href={reply.reply_website} target="_blank">
                                    @{reply.reply_nickname}
                                  </a>
                                )}
                              </>
                            ) : null}
                            <span>{reply.content}</span>
                          </div>
                        </div>
                      </div>
                    );
                  })}

                  {/* 回复框 */}
                  <CommentField
                    ref={(ref) => {
                      if (ref) replyFieldRefs.current[idx] = ref;
                    }}
                    show={false}
                    type={type}
                    topicId={topicId}
                    afterSubmit={() => {
                      reloadReplies(idx);
                    }}
                  />
                </div>
              </div>
            );
          })}
          {/* 加载更多 */}
          {listLoading ? (
            <div className="loading-more animate-spin">
              <Spin
                indicator={
                  <LoadingOutlined
                    style={{
                      fontSize: "5.5rem",
                    }}
                    spin
                  />
                }
              />
            </div>
          ) : null}
        </div>
      ) : (
        <div style={{ textAlign: "center", fontSize: "5rem" }}>
          暂无评论，来发评论吧~
        </div>
      )}
    </Styled>
  );
};

export default Comment;
